import { invokeChannel, invokeChannel2 } from "@/framework/ipc/util.ts";
import type { FileWriteStartArgs } from "@common/file-write-service-types.ts";
import path from "@/framework/util/path.ts";

/**
 * 复制文件
 * @param src 源文件路径
 * @param destDir 目标目录
 * @param destSubDir 目标子目录
 * @return 目标文件路径
 */
export async function copyFile(src: string, destDir: string, destSubDir?: string): Promise<string> {
  if (destSubDir) {
    destDir = path.join(destDir, destSubDir);
  }
  const filename = path.basename(src);
  const dest = path.join(destDir, filename);

  if (!(await native.fs.exists(destDir))) {
    await native.fs.mkdir(destDir, { recursive: true });
  }

  if (!(await native.fs.exists(dest))) {
    await native.fs.copyFile(src, dest);
  }

  return dest;
}

/**
 * 流式写入文件接口
 * @remarks 需要主进程引入fs-stream-writer.ts
 */
export const FileWriterStreamAPI = {
  start: (args: FileWriteStartArgs) => invokeChannel("fs.stream.writer.start", args),
  write: (chunk: string | Uint8Array) => invokeChannel2("fs.stream.writer.write", chunk),
  close: () => invokeChannel("fs.stream.writer.close"),
};
